package com.tanhua.server.service;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.api.PeachblossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Sound;
import com.tanhua.model.vo.SoundVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class PeachblossomService {

    @DubboReference
    private PeachblossomApi peachblossomApi;
    @Autowired
    private FastFileStorageClient client;
    @Autowired
    private FdfsWebServer webServer;

    @DubboReference
    private UserInfoApi userInfoApi;
    //接收语音
    public SoundVo receive() {
        Long listenId = UserHolder.getUserId();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        //查询不是当前用户的发的语音
        Sound sound = peachblossomApi.receive(listenId,date);
        //查询该语音用户的信息
        UserInfo userInfo = userInfoApi.findById(sound.getUserId());
        //查询当前用户接收了几次
        Integer num = 10;

        Integer count = peachblossomApi.find(listenId, date);
        //创建vo
        SoundVo vo = SoundVo.init(userInfo, sound);
        vo.setRemainingTimes(num-count);
        return vo;
    }
    //保存语音
    public void save(MultipartFile soundFile) throws IOException {
        Long userId = UserHolder.getUserId();
        //上传fastdfs
        //名字
        String filename = soundFile.getOriginalFilename();
        //后缀
        int index = filename.lastIndexOf(".");
        filename = filename.substring(index + 1);
        //文件上传
        StorePath storePath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), filename, null);
        //拼接地址
      String soundUrl =  webServer.getWebServerUrl() + storePath.getFullPath();
        //构造对象 保存
        //今天日期

        Sound sound = new Sound();
        sound.setUserId(userId);
        sound.setSoundUrl(soundUrl);
        sound.setDate(null);
        sound.setListenId(null);
        sound.setHasRead(0);


        peachblossomApi.save(sound);
    }
}
